package service

import (
	"shop/common/log"
	"shop/dao"
	"shop/entity"
	"shop/utils/result"
	"shop/utils/sessionutil"
)

// GetUserInfo 获取用户信息，has cache
func GetUserInfo(userId int64) *entity.User {
	user := sessionutil.GetUserInfoFromCache(userId)
	if user.Id == userId {
		return user
	}
	dao.GetDB().Model(user).Where("id", userId).Take(user)
	sessionutil.SetUserInfoCache(user)
	return user
}

func UpdateUser(user *entity.UserFilter, userId int64) *result.Result {
	err := dao.GetTx().Table(entity.TableNameUser).Where("id", userId).Updates(&entity.UserFilter{
		Phone:   user.Phone,
		Name:    user.Name,
		Address: user.Address,
		Avatar:  user.Avatar,
		Sex:     user.Sex,
	}).Commit().Error
	if err != nil {
		return result.Fail(err.Error())
	}
	sessionutil.Logout(userId)
	sessionutil.SetUserInfoCache(GetUserInfo(userId))
	return result.Ok(nil)
}

func SetUserLoginTime(userId int64, time int64) {
	err := dao.GetDB().Table(entity.TableNameUser).Where("id", userId).UpdateColumn("last_login_time", time).Error
	if err != nil {
		log.Errorf("fail to SetUserLoginTime, userId=%d, time=%d, db err: %v", userId, time, err)
	}
}
